package io.renren.modules.ProjectControl.Service;

import io.renren.modules.ProjectControl.Service.ExeCommandService.ExeServiceP1;
import io.swagger.models.auth.In;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Service
public class ExeCommandP1 implements ExeServiceP1 {
    private static Process exe;
    private static long pid;
    private List<Integer> ports;
    @Override
    public void Start(String Command) throws IOException, InterruptedException {
        Runtime runtime = Runtime.getRuntime();
       runtime.exec(Command);
    }

    @Override
    public String Stop(String Command) throws IOException {

        Runtime runtime = Runtime.getRuntime();
        runtime.exec(Command);
        return "StopP1";
    }

    @SneakyThrows
    @Override
    public String Status() throws IOException {
            this.ports=new ArrayList<Integer>();
            this.ports.add(8899);
        Set<Integer> pids = new HashSet<>();

        for (int port :this.ports) {
            Runtime runtime = Runtime.getRuntime();
            System.out.println(port);
            Process process = runtime.exec("cmd /c netstat -ano | findstr \""+port+"\"");


            List<String> read = read(process.getInputStream(), "UTF-8");
            if (read.size() == 0) {
                System.out.println("找不到该端口的进程");
            } else {
                for (String string : read) {
                    System.out.println(string);
                }
                System.out.println("找到" + read.size()/2 + "个进程");

            }

            for (String line : read) {
                int offset = line.lastIndexOf(" ");
                String spid = line.substring(offset);
                spid = spid.replaceAll(" ", "");
                int pid = 0;
                try {
                    pid = Integer.parseInt(spid);
                } catch (NumberFormatException e) {
                    System.out.println("获取的进程号错误:" + spid);
                }
                pids.add(pid);
            }
        }
        System.out.println(pids);


        return pids.toString();
    }


    private List<String> read(InputStream in, String charset) throws IOException{
        List<String> data = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
        String line;
        while((line = reader.readLine()) != null){
                data.add(line);
        }
        reader.close();
        return data;
    }
}
